import json
from .response import ApiResponse
from rest_framework.renderers import JSONRenderer


class ApiResponseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # Skip non-API requests (checking path prefix)
        if not request.path.startswith('/api/'):
            return response

        # Ensure response is rendered
        if hasattr(response, 'render') and not response.is_rendered:
            response.accepted_renderer = JSONRenderer()
            response.accepted_media_type = "application/json"
            response.renderer_context = {}
            response = response.render()

        # Convert to ApiResponse if needed
        if not isinstance(response, ApiResponse):
            try:
                content = response.content.decode() if hasattr(response, 'content') else str(response)
                data = json.loads(content) if content else {}
                response = ApiResponse(
                    data=response.data if hasattr(response, 'data') else data,
                    message=getattr(response, 'message', 'success'),
                    code=response.status_code
                )
            except Exception:
                response = ApiResponse(
                    data={'content': content} if 'content' in locals() else {},
                    code=response.status_code,
                    message=getattr(response, 'reason_phrase', '')
                )

        # Ensure final response is rendered
        if hasattr(response, 'render') and not response.is_rendered:
            response.render()
            
        return response
    # def process_view(self, request, callback, callback_args, callback_kwargs):
    #     # 豁免PUT请求的CSRF验证
    #     if request.method == 'PUT':
    #         return None
    #     return super().process_view(request, callback, callback_args, callback_kwargs)